﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BSCMFF.Core.DataAccessLayer;
using Telerik.Web.UI;
using System.Drawing;

namespace BSCMFF.Web.Pages.Reporting
{
    public partial class TopCompetencyEmployees : BSCMFF.Core.MultiLanguagePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (EvalSelection.PublicSelectedValue != 0)
            {
                
                PanelRewards.Visible = true;

                BSCEntities context = new BSCEntities();
                Evaluation_Period ep = (from eps in context.Evaluation_Period
                                        where eps.ID == EvalSelection.PublicSelectedValue
                                        select eps).SingleOrDefault();
                

                SetBordersForEvaluation(ep);

                if (ep.Competencies != true || ep.Reward ==false)
                {
                    LabelNoCompetencyReward.Visible = true;
                    RadGridCompetencies.Visible = false;
                }
                else
                {
                    LabelNoCompetencyReward.Visible = false;
                    double bonus = CalculateBonusPerEmployeer(ep);
                    if (bonus != 0)
                    {
                        RadGridCompetencies.Visible = true;
                        FillTopEmployeesCompetencyGrid(ep, bonus);
                    }
                    else
                    {

                    }
                }       
             }
        }

        private double CalculateBonusPerEmployeer(Evaluation_Period ep)
        {
            LabelNumberOfEmployees2.Text = ep.CompetencyTop + "% of Employees";
            BSCEntities context = new BSCEntities();

            decimal totalBonus = (decimal)ep.TotalBonus;
            //RadNumericTextBoxTotalBonus.Value = (double)totalBonus;
            decimal competenciesBonus = ep.PKPIs == false ? totalBonus : totalBonus * (decimal)ep.BonusSliderValue / 100;

            RadNumericTextBoxBonusCompetencies.Value = (double)competenciesBonus;

            List<int> userIDs = (from eee in context.Evaluation_Evaluator_Employee
                                 where eee.Evaluation_FK == ep.ID
                                 select eee.Employee_FK).Distinct().ToList();
            int numberOfEvaluatedEmployees = 0;
            if (userIDs != null)
            {
                numberOfEvaluatedEmployees = (int)(userIDs.Count / (double)ep.CompetencyTop);
            }
            RadNumericTextBoxNumberOfEmployees2.Value = numberOfEvaluatedEmployees;

            if (numberOfEvaluatedEmployees != 0)
            {
                double bonusPerEmployee = (double)RadNumericTextBoxBonusCompetencies.Value / numberOfEvaluatedEmployees;
                RadNumericTextBoxBonusPerEmployee2.Value = bonusPerEmployee;
                double result = (double)RadNumericTextBoxBonusCompetencies.Value / (double)numberOfEvaluatedEmployees;// / (double)ep.CompetencyTop;

                RadNumericTextBoxCompetencyPossibleBonus.Value = result;
                return result;
            }

            else
            {
                return 0;
            }
        }

        private void SetBordersForEvaluation(Evaluation_Period ep)
        {
            int topPercent = (int)ep.CompetencyTop;
            int bottomPercent = 10;
            BSCEntities context = new BSCEntities();
            int numberOfEmployees = (from eee in context.Evaluation_Evaluator_Employee
                                    where eee.Evaluation_FK == ep.ID
                                    select eee.ID).Count();

            int top = numberOfEmployees * topPercent / 100;
            int bottom = numberOfEmployees - ( numberOfEmployees *  bottomPercent / 100);

            HiddenFieldTop.Value = top.ToString();
            HiddenFieldBottom.Value = bottom.ToString();
            HiddenFieldCurrent.Value = "0";
        }

        private void FillTopEmployeesCompetencyGrid(Evaluation_Period ep, double bonuss)
        {
            BSCEntities context = new BSCEntities();
            //Evaluation_Period ep;

            //if (EvalSelection.PublicSelectedValue == 0)
            //{
            //    return;
            //}
            //else
            //{
            //    ep = (from temp in context.Evaluation_Period
            //                            where temp.ID == evalID
            //                            select temp).SingleOrDefault();
            //}
            //if (ep.Reward != true)
            //{
            //    return;
            //}

            var data = (from ev in context.Evaluation_User_Question_Value
                        join ee in context.Evaluation_Evaluator_Employee on ev.EEE_FK equals ee.ID
                        where ee.Evaluation_FK == ep.ID && ee.Evaluated == true
                        join eq in context.Evaluation_Question on ev.Evaluation_Question_FK equals eq.ID
                        join ec in context.Evaluation_Category on eq.Evaluation_Category_FK equals ec.ID
                        group ev by new {ee.Employee_FK} into g
                        join u in context.Users on g.Key.Employee_FK equals u.ID
                        join epp in context.Evaluation_Period on ep.ID equals epp.ID
                        orderby g.Sum(ev => ev.Value - ev.Evaluation_Question.Evaluation_Category.Min) * 100 / g.Sum(ev => ev.Evaluation_Question.Evaluation_Category.Max - ev.Evaluation_Question.Evaluation_Category.Min) descending
                        select new
                        {
                            Fullname = u.Firstname + u.Lastname,
                            perc = g.Sum(ev => ev.Value - ev.Evaluation_Question.Evaluation_Category.Min)*100/g.Sum(ev => ev.Evaluation_Question.Evaluation_Category.Max - ev.Evaluation_Question.Evaluation_Category.Min),
                        
                            //salary = u.Salary == null ? 0 : (int)u.Salary,
                            bonus = 0// bonuss//u.Salary == null ? 0 : (int)(u.Salary * epp.CompetencyCoef / 100)
                        }).ToList();

            

            int topPercent = (int)ep.CompetencyTop;
            int coef = (int)ep.CompetencyCoef;

            int totalEvaluatedEmployees = data.Count;

            int i = 0;
            List<HelpClasss2> hclass = new List<HelpClasss2>();

            foreach (var d in data)
            {
                HelpClasss2 hc = new HelpClasss2();
                hc.Fullname = d.Fullname;
                hc.Competency = d.perc;
                if (i++ < RadNumericTextBoxNumberOfEmployees2.Value)
                {
                    //string fn = d.Fullname;
                    hc.Bonus = bonuss;
                }
                else
                {
                    hc.Bonus = 0;
                }
                hclass.Add(hc);
            }

            RadGridCompetencies.DataSource = hclass;// data;
            RadGridCompetencies.DataBind();
        }

        protected void RadGridCompetencies_ItemDataBound(object sender, GridItemEventArgs e)
        {
            //int curr = Int32.Parse(HiddenFieldCurrent.Value);
            //int botom = Int32.Parse(HiddenFieldBottom.Value);
            //int top = Int32.Parse(HiddenFieldTop.Value);

            
            if (e.Item is GridDataItem)
            {
                GridDataItem item = e.Item as GridDataItem;
                //if (curr <= top)
                //{
                //    item.BackColor = Color.LightGreen;

                //}
                //if (curr > top && curr <= botom)
                //{
                //    item.BackColor = Color.LightYellow;
                //    //item["Bonus"].Visible = false;
                //    ((Label)item["LabelBonus"].FindControl("LabelBonus")).Text = "0";
                //}
                //if (curr > botom)
                //{
                //    item.BackColor = Color.Pink;
                //    ((Label)item["LabelBonus"].FindControl("LabelBonus")).Text = "-" + ((Label)item["LabelBonus"].FindControl("LabelBonus")).Text;
                //}

                //HiddenFieldCurrent.Value = (++curr).ToString();


                total += Int32.Parse(((Label)item["LabelBonus"].FindControl("LabelBonus")).Text);
            }

            if (e.Item is GridFooterItem)
            {
                GridFooterItem footerItem = e.Item as GridFooterItem;
                footerItem["LabelBonus"].Text = "total: " + total.ToString();
            }
        }
        int total = 0;
    }
    class HelpClasss2
    {
        public string Fullname { get; set; }
        public int Competency { get; set; }
        public double Bonus { get; set; }
    }
}